# coding:utf-8
from sqlalchemy import Column, String, Integer, and_

from database import dbconnect, session_maker, model_list, model_dict

_, _, DBase = dbconnect()


class CloudDepartment(DBase):
    __tablename__ = 'c_department'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    department = Column(String(255))
    department_name = Column(String(255))
    access_key_id = Column(String(255))
    access_key_secret = Column(String(255))
    cloud_id = Column(String(255))
    status = Column(String(255))
    aliyunid = Column(String(255))


# 查询所有
def find_all_depart():
    with session_maker() as session:
        result = session.query(CloudDepartment).all()
        return model_list(result)


# 返回一个根据部门账号，获取ak，sk的字典
def get_depart_account_dict() -> dict:
    account_dict = {}
    with session_maker() as session:
        result = session.query(CloudDepartment).all()
        res = model_list(result)
        for row in res:
            account_dict[row['aliyunid']] = {
                "access_key_id": row['access_key_id'],
                "access_key_secret": row['access_key_secret'],
                "department": row['department'],
                "department_name": row['department_name'],
                "cloud_id": row['cloud_id'],
                "odps_projects": []
            }
    return account_dict



# 根据id查询
def find_depart_by_id(cloud_id, depart_id):
    with session_maker() as session:
        row = session.query(CloudDepartment).filter(and_(
            CloudDepartment.cloud_id == cloud_id,
            CloudDepartment.department == depart_id
        )).first()
        return model_dict(row)


def add_depart(cloud_id, depart_id):
    print("add depart")
    with session_maker() as session:
        count = session.query(CloudDepartment).filter(and_(
            CloudDepartment.cloud_id == cloud_id,
            CloudDepartment.department == depart_id
        )).count()
        if count == 0:
            new_cluster = CloudDepartment(department=depart_id, cloud_id=cloud_id)
            session.add(new_cluster)
        return 'ok'
